package controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import entity.Student;
import entity.User;
import util.JDBCUtil;
import util.JSONUtil;

@WebServlet("/user")
public class UserServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		switch (method) {
		case "login":
			login(req, resp);
			break;
		case "logout":
			logout(req, resp);
			break;
		case "checkExist":
			checkExist(req, resp);
			break;
		default:
			break;
		}
	}

	private void checkExist(HttpServletRequest req, HttpServletResponse resp) {
		System.out.println("UserServlet.checkExist()");
		String name = req.getParameter("name");
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		int count = 0;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "SELECT count(*) FROM `user` WHERE `name`=?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, name);
			System.out.println(preparedStatement);
			resultSet = preparedStatement.executeQuery();
			while (resultSet.next()) {
				// count = resultSet.getInt("count(*)");
				count = resultSet.getInt(1);// 1：代表第一列
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, resultSet);
		}
		
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		if (count >= 1) {
			map.put("isExist", true);
			JSONUtil.obj2Json(map, resp);
		} else {
			map.put("isExist", false);
			JSONUtil.obj2Json(map, resp);
		}
	}

	private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("UserServlet.logout()");
		HttpSession session = req.getSession(false);
		if (session != null) {
			// session.invalidate();
			
			session.removeAttribute("user");
			
			// 重定向到登录界面
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
		}
	}

	private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// 等根据用户名和密码登录之前，首先验证用户输入的验证码对不对
		String checkCode = req.getParameter("checkCode");
		HttpSession session = req.getSession();
		String checkCodeInSession = (String) session.getAttribute("checkCodeInSession");
		if (checkCode == null 
				|| "".equals(checkCode) 
				|| !checkCode.equals(checkCodeInSession)) {
			// 如果用户输入的验证码为null或者空字符串，或者输入的验证码和生成的不一致，
			// 就在跳转到登录界面，后面的代码不需要再执行了
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
			return;
		}
		
		
		String userName = req.getParameter("name");
		String userPassword = req.getParameter("password");
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		User user = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "SELECT `id`,`name`,`password` FROM `user` WHERE `name`=? and `password`=?";
			// 预编译
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, userName);
			preparedStatement.setString(2, userPassword);
			System.out.println(preparedStatement);
			resultSet = preparedStatement.executeQuery();
			// 打印statement对象可以打印出执行的sql语句
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				String password = resultSet.getString("password");
				
				user = new User(id, name, password);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, resultSet);
		}
		
		if (user != null) {// 有这个用户，登录成功
			// 判断用户是否登录的凭证
			session.setAttribute("user", user);
			
			resp.sendRedirect(req.getContextPath() + "/index.jsp");
		} else {// 没有这个用户登录失败
			resp.sendRedirect(req.getContextPath() + "/fail.jsp");
		}
		
	}
}
